package com.xexun.gpstracker.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.EditText;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.AppManager;
import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.common.MyConstants;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.pojo.User;
import com.xexun.gpstracker.util.JSONHelper;
import com.xexun.gpstracker.util.Utils;

/**
 * 功能：使用ViewPager实现初次进入应用时的引导页
 * <p/>
 * (1)判断是否是首次加载应用--采取读取SharedPreferences的方法
 * (2)是，则进入引导activity；否，则进入LoginActivity
 * (3)2s后执行(2)操作
 *
 * @author huangfei
 */
public class LauncherActivity extends Activity {
    private String TAG = LauncherActivity.class.getSimpleName();
    private SharedPreferences msharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading_layout);
        Log.i(Constants.TAG, "LauncherActivity onCreate！");
        msharedPreferences = Utils.getPreferences(this);


        skip();

//
//        boolean mFirst = isFirstEnter(LauncherActivity.this,LauncherActivity.this.getClass().getName());
//        if(mFirst&&!isBaseUrl())
//            inputTitleDialog("请输入appKey");
//        else
//            new Handler().postDelayed(() -> skip(), 3000);




    }

    private void skip() {


        Intent mIntent = new Intent();
        if(AppContext.isEntered){
            Activity activity = AppManager.getAppManager().currentActivity();
            String name = activity.getLocalClassName();
            Log.i(Constants.TAG, "启动已存在的activity："+name);
            mIntent.setClass(LauncherActivity.this, activity.getClass());
            mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        }else {
            if(AppManager.getAppManager().haveActivity()) {
                AppManager.getAppManager().finishAllActivity();
            }

            mIntent.setClass(LauncherActivity.this, LoginActivity.class);
//          mIntent.setClass(LauncherActivity.this, MainActivity.class);
        }
        startActivity(mIntent);
        finish();
    }


    private void inputTitleDialog(String title) {

        final EditText inputServer = new EditText(this);
        inputServer.setFocusable(true);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title).setView(inputServer);
        builder.setPositiveButton(getString(R.string.record_save_dialog_ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String inputName = inputServer.getText().toString();

                        getServerIP(inputName);
                    }
                });
        builder.show();
    }


    private void getServerIP(String key){
        Log.i(TAG,"key="+key);
        if (" ".equals(key)||key.length()==0||key ==null){
            inputTitleDialog("请输入正确的appKey");
            return;
        }

        User.getServerIP(this, key, new HttpCallback() {
            @Override
            public void onSuccess(ResponseData obj) throws Exception {
                Log.i(TAG, obj.toString());
                if (obj.getRetcode() == 0) {
                    String serverIP = JSONHelper.getString(obj.getBody(),"ip");
                    String serverPort = JSONHelper.getString(obj.getBody(),"port1");
                    String tcpPort = JSONHelper.getString(obj.getBody(),"port2");
                    SharedPreferences.Editor edit = msharedPreferences.edit();
                    edit.putString(MyConstants.SERVER_IP, serverIP);
                    edit.putString(MyConstants.SERVER_PORT, serverPort);
                    edit.putString(MyConstants.TCP_PORT, tcpPort);
                    edit.apply();

                    skip();

                }else {
                    inputTitleDialog("验证失败，请重新输入appkey");
                }


            }

            @Override
            public void onFailure(String message) throws Exception {
                Log.i(TAG, message);
                inputTitleDialog("验证失败，请重新输入appkey");
            }
        });





    }


//    ****************************************************************
//     判断应用是否初次加载，读取SharedPreferences中的guide_activity字段
//    ****************************************************************
    private static final String SHAREDPREFERENCES_NAME = "my_pref";
    private static final String KEY_GUIDE_ACTIVITY = "guide_activity";
    private boolean isFirstEnter(Context context, String className){
        if(context==null || className==null||"".equalsIgnoreCase(className)) return false;
        String mResultStr = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_WORLD_READABLE).getString(KEY_GUIDE_ACTIVITY, "");//取得所有类名 如 com.my.MainActivity
        if(mResultStr.equalsIgnoreCase("false"))
            return false;
        else
            return true;
    }


    private boolean isBaseUrl(){
        String url = msharedPreferences.getString(MyConstants.SERVER_PORT, null);
        if (url == null){
            return false;
        }else {
            return true;
        }

    }

    //*************************************************
    // Handler:跳转至不同页面
    //*************************************************
//    private final static int SWITCH_MAINACTIVITY = 1000;
//    private final static int SWITCH_GUIDACTIVITY = 1001;
//    public Handler mHandler = new Handler(){
//        public void handleMessage(Message msg) {
//            switch(msg.what){
//            case SWITCH_MAINACTIVITY:
//                Intent mIntentMain = new Intent();
//                mIntentMain.setClass(LauncherActivity.this, LoginActivity.class);
//                LauncherActivity.this.startActivity(mIntentMain);
//                LauncherActivity.this.finish();
//                break;
//            case SWITCH_GUIDACTIVITY:
//                Intent mIntentGUID = new Intent();
//                mIntentGUID.setClass(LauncherActivity.this, GuideActivity.class);
//                LauncherActivity.this.startActivity(mIntentGUID);
//                LauncherActivity.this.finish();
//                break;
//            }
//            super.handleMessage(msg);
//        }
//    };

}
